const express = require('express');
const md5 = require('md5');
const userModel = require('../../model/userModel');

const router = express.Router();

//创建登录页面路由
router.get('/login', (req, res) => {
    res.render('auth/login');
})

//创建登录完成路由
router.post('/login', (req, res) => {
    let { username, password } = req.body;

    //检测


    userModel.findOne({ username: username, password: md5(password) }).then(data => {
        if (!data) {
            return res.render('success', { message: '账号或密码错误，登录失败···', url: '/login' });

        }
        //写入session
        req.session.username = data.username;
        req.session._id = data.id;

        res.render('success', { message: '登录成功', url: '/account' });




    }, error => {
        res.status(500).send(`失败···，请稍后在试 ${error.message}`);
    }
    )

})

//退出路由
router.post('/logout', (req, res) => {
    req.session.destroy();

    res.render('success', { message: '退出成功', url: '/login' });
})
//导出路由
module.exports = router;